package com.cskaoyan.config;

import com.cskaoyan.shiro.CustomRealm;
import com.cskaoyan.shiro.MallToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

public class CustomAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        this.assertRealmsConfigured();
        // 原始的realms
        ArrayList<Realm> originRealms = (ArrayList<Realm>) this.getRealms();
        // 对realms进行分发
        MallToken mallToken = (MallToken)authenticationToken;
        String type = mallToken.getType();
        ArrayList<Realm> realms = new ArrayList<>();
        // 遍历原始的realms，看指定的realms是否在其中
        for (Realm originRealm : originRealms) {
            // 判断当前realm是否包含指定的type，是就添加
            if(originRealm.getName().toLowerCase().contains(type)){
                realms.add(originRealm);
            }
        }
        // 有值就处理，否则返回空
        return realms.size() == 1 && !(realms.get(0) instanceof CustomRealm) ? this.doSingleRealmAuthentication((Realm) realms.iterator().next(),authenticationToken):
                this.doSingleRealmAuthentication((Realm) originRealms.get(0),authenticationToken);

    }
}
